package com.jt.blog.webconf;

import com.jt.blog.common.constant.ImageTypePrefix;
import com.jt.blog.interceptor.InitInterception;
import com.jt.blog.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.MultipartConfigElement;
import java.io.File;

/**
 * @author : 戴瑞
 * @create 2016-08-29 13
 **/
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    /**
     *  文件的上传路径也是文件的路径
     */
    @Value("${upload-file-path}")
    private String commonFilePath;

    /**
     *  ckEdit文件的上传路径
     */
    @Value("${upload-blogFile-path}")
    private String blogFilePath;

    @Value("${file-temp-path}")
    private String tempFile;

    @Bean
    InitInterception initInterception() {
        return new InitInterception();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/back/**").excludePathPatterns("/back/login/**", "/back/logout/**");
        //registry.addInterceptor(initInterception()).addPathPatterns("/**").excludePathPatterns("/back/**","/back/login/**", "/back/logout/**");
        super.addInterceptors(registry);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(ImageTypePrefix.NORMAL.getPath()+"/**").addResourceLocations("file:"+commonFilePath+ File.separator);
        registry.addResourceHandler(ImageTypePrefix.BLOG.getPath()+"/**").addResourceLocations("file:"+blogFilePath+ File.separator);
        super.addResourceHandlers(registry);
    }

    /**
     * 配置文件上传的临时路劲，防止出错
     * @return
     */
    @Bean
    MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setLocation(tempFile);
        return factory.createMultipartConfig();
    }
}

